package impl

import (
	"context"

	"gitee.com/go-course/go8/projects/devcloud/cmdb/apps/resource"
)

func (s *service) SaveResource(ctx context.Context, res *resource.Resource) (
	*resource.Resource, error) {
	// 比如检查
	if err := res.Validate(); err != nil {
		return nil, err
	}

	// 入库
	err := s.save(ctx, res)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (s *service) QueryResource(ctx context.Context, req *resource.QueryResourceRequest) (
	*resource.ResourceSet, error) {
	// 首先查询Meta表
	// LEFT JOIN

	// 都是用orm, JOIN
	// 完全使用SQL
	// 	SELECT
	// 	*
	// FROM
	// 	resource_meta m
	// 	LEFT JOIN resource_spec s ON s.resource_id = m.resource_id
	// 	LEFT JOIN resource_cost c ON c.resource_id = m.resource_id
	// 	LEFT JOIN resource_status t ON t.resource_id = m.resource_id
	// WHERE m.resource_id='instance_01';
	// orm作为SQL builder 来构建复杂SQL
	query := s.db.WithContext(ctx).Table("resource_meta m").
		Joins("LEFT JOIN resource_spec s ON s.resource_id = m.resource_id").
		Joins("LEFT JOIN resource_cost c ON c.resource_id = m.resource_id").
		Joins("LEFT JOIN resource_status t ON t.resource_id = m.resource_id")
	if req.Domain != "" {
		query = query.Where("m.domain = ?", req.Domain)
	}
	if req.Namespace != "" {
		query = query.Where("m.namespace = ?", req.Namespace)
	}
	if req.Env != "" {
		query = query.Where("m.env = ?", req.Env)
	}
	if req.Status != "" {
		query = query.Where("m.env = ?", req.Env)
	}
	if req.Type != nil {
		query = query.Where("s.resource_type = ?", req.Env)
	}
	if len(req.ResourceIds) > 0 {
		query = query.Where("m.resource_id IN (?)", req.ResourceIds)
	}
	if req.Keywords != "" {
		// SQL LIKE '%name%' % .*
		query = query.Where(
			"s.name LIKE ? OR t.private_ip LIKE ?",
			"%"+req.Keywords+"%",
			req.Keywords+"%",
		)
	}

	temp := NewResourceSet()
	err := query.
		Order("m.create_at DESC").
		Offset(int(req.Page.ComputeOffset())).
		Limit(int(req.Page.PageSize)).
		Scan(&temp.Items).
		Error

	if err != nil {
		return nil, err
	}

	// 数据库里面的数据 和 接口的数据不一定匹配
	// 需要在Dao进行转换
	set := temp.ResourceSet()

	// 统计有多少条
	err = query.Count(&set.Total).Error
	if err != nil {
		return nil, err
	}
	return set, nil
}
